import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ApiService } from '../api/api.service';
import { ApiUrl } from '../api/ApiUrl';
import { BankVO } from '../vo/BankVO';
@Component({
  selector: 'app-banklist',
  templateUrl: './banklist.page.html',
  styleUrls: ['./banklist.page.scss'],
})
export class BanklistPage implements OnInit {
  items: BankVO[] = [];
  goToDetails(iid) {
    this.router.navigate(['/guwendetails', {'iid': iid}]);
  }
  goToMore(iid, cname) {
    this.router.navigate(['/guwenmore', {'iid': iid, 'cname': cname}]);
  }
  constructor(private router: Router, public api: ApiService) { }
  ngOnInit() {
    this.doDownRefresh(null);
  }
  // 下拉刷型界面
  doDownRefresh(evt) {
    if (evt === null) {
      this.onSearch('0', evt);
    } else {
      console.log('iid:' + this.items[0].iid);
      this.onSearch(this.items[0].iid, evt);
    }
  }
  onSearch(iid: string = '0', evt: any, opt: string = 'down') {
    this.api.getItems<BankVO>(ApiUrl.getBankList, { 'iid': iid, 'option': opt }).subscribe(response => {
      if (evt) {
        evt.target.complete();
      }
      if (response === null || response.length === 0) {
        console.log('没有数据返回');
        return;
      }
      console.log(opt);
      console.log(response);
      if (opt === 'down') { // 下拉刷新，把items追加到新的数据的尾部
        // this.items = this.items.concat(response);
        this.items = response.concat(this.items);
      } else {
        this.items = this.items.concat(response);
        // this.items = this.items.splice(0, 0, response);
      }
      for (let i = 0; i < this.items.length; i++) {
        for (let j = 0; j < this.items[i].clist.length; j++) {
          this.items[i].clist[j].cpicpath = ApiUrl.guwenUrl + this.items[i].clist[j].cpicpath;
        }
      }
    }, () => {
      if (evt) {
        evt.target.complete();
      }
      console.log('出错了');
    });
  }
  doUpRefresh(evt) {
    console.log('上拉刷新');
    this.onSearch(this.items[this.items.length - 1].iid, evt, 'up');
  }

}
